import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import NavigationBar from '../../../components/navigationBar/index';
import { goodsPurchase, } from '../../../services/goods';
import { tempOrder, orderConfirm, orderPay, testPay } from '../../../services/order';

import './index.scss'
import { fullImgUrl, timeFormat } from '../../../utils/utils';
import Right from './img/icon_right.png';
import Address from './img/icon_address.png';
import IconBorder from '../../../static/home/shopc.png';
import discount from './img/discount.png';



export default class Index extends Component {
    config = {
        navigationBarTitleText: '结算中心',
        type: this.$router.params.id,
    }

    state = {
        list: [],
        tempOrderInfo: null,
        balance: Taro.getStorageSync('userInfo').balance,
        isMore: false,
        navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
        member_level: Taro.getStorageSync('userInfo').member_level,
        deliveryTime: '',
        startDeliveryTime: ''
    };
    componentWillMount() {
        let date = new Date();
        date.setDate(date.getDate() + 1);
        // 下午三点半以后，后天再发货
        if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
            date.setDate(date.getDate() + 1);
        }
        this.setState({
            startDeliveryTime: timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy-MM-dd')
        })
        this.setState(
            {
                code: this.$router.params.code || '',
            },
            () => {
                Taro.removeStorageSync('deliveryTime');
            }
        );
    }
    componentDidShow() {
        this.init()
    }
    init() {
        var pageObj = {
            sku_id: this.$router.params.sku_id,
            num: this.$router.params.num,
            goods_type: this.$router.params.goods_type,
        }
        // var cart_ids = this.$router.params.cart_ids.split(",")
        // var cart_ids="12,13,14"
        // var arr = []
        // cart_ids = cart_ids.split(",");
        // cart_ids.forEach(element => {
        //     arr.push(parseInt(element))
        // });
        goodsPurchase(pageObj).then(res => {
            this.setState({
                tempOrderInfo: res,
            });
            // res.has_sku.forEach((item, index) => {
            //   item.cover = fullImgUrl(item.cover)
            // })

        })
    }
    editAddress() {
        Taro.navigateTo({
            url: '/subPackageWork/pages/my-address/index?isEdit=1',
        });
    }
    dateChange(e) {
        if (e.detail.value == '2021-02-11' || e.detail.value == '2021-02-12' || e.detail.value == '2021-02-13') {
            Taro.showToast({
                title: '春节期间不发货,请重新选择发货时间!',
                icon: 'none'
            });

        } else {
            let temp = e.detail.value.split('-');
            this.setState({
                deliveryTime: `${temp[0]}年${temp[1]}月${temp[2]}日`
            })
        }
    }
    confirmOrder() {
        if (!this.state.deliveryTime) {
            Taro.showToast({
                title: '请选择发货时间!',
                icon: 'none'
            });
        } else {
            // 订阅通知授权
            // 下单购买
            // 1. 新订单通知 dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ
            // 2. 发货通知 m_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ
            // 3. 收货通知 1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g
            var deliveryTime = this.state.deliveryTime;
            Taro.requestSubscribeMessage({
                tmplIds: ['dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ', 'm_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ', '1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g'],
                complete: function (subRes) {
                    orderConfirm({
                        delivery_time: deliveryTime,
                    }).then(res => {
                        orderPay({
                            order_id: res.order_info_id,
                            pay_type: 3, // 连连支付
                            // pay_type: 1,
                            pay_platform: 1,
                        }).then(data => {
                            if (data == "此订单无需支付") {
                                Taro.redirectTo({
                                    url: '/pages/my-order/index',
                                });
                            }
                            Taro.requestPayment({
                                ...JSON.parse(data.payload).metadata,
                                // ...data,
                                success() {
                                    Taro.redirectTo({
                                        url: '/pages/my-order/index',
                                    });
                                },
                                fail() {
                                    Taro.redirectTo({
                                        url: '/pages/my-order/index',
                                    });
                                },
                            });
                        });
                    });
                },
            });
        }
    }
    render() {
        const { tempOrderInfo, code, deliveryTime, member_level, } = this.state;
        return tempOrderInfo ? (
            <View className='settlement' style={`margin-top: ${navigationBarHeight}`} >
                <NavigationBar text='结算中心' type="activity" />

                <View className="chunk">
                    {/* <View className=""> */}
                    <Image className="icon" src={Address}></Image>
                    {/* </View> */}

                    <View className="content">
                        <View className="layout">
                            <View className="sett-title">{tempOrderInfo.address.province_name}{tempOrderInfo.address.city_name}</View>
                            <View className="sett-title">{tempOrderInfo.address.region_name}</View>
                        </View>
                        <View className="layout">
                            <View className="sett-title">{tempOrderInfo.address.receiver}</View>
                            <View className="sett-title">{tempOrderInfo.address.mobile}</View>
                            <View className="nextFont" onClick={this.editAddress}>选择地址<Image className="next" src={Right}></Image></View>

                        </View>

                    </View>
                </View>
                <View className="main">
                    <View className="logo">
                        <Image className="icon" src={IconBorder}></Image>
                        <View className="text">中鹿岛</View>
                    </View>
                    {
                        tempOrderInfo.goods.map(res => (
                            <View className="center">
                                <View className="goodlsit-top">
                                    {res.goods_type == 0 ? (
                                        <Image className="images" src={fullImgUrl(res.sku.fish_cover)}></Image>
                                    ) : (
                                        <Image className="images" src={fullImgUrl(res.sku.card_cover)}></Image>
                                    )}                                    <View className="right">
                                        <View className="tittle">{res.sku.attr_str}·{res.sku.goods_name}</View>
                                        {/* <View className="small">小而精美</View>
                            <View className="small">家宴定制</View> */}
                                        <View className="layout">
                                            <View className="small">X{res.num}</View>
                                            <View className="money">￥ {res.num * res.sku.price}</View>
                                        </View>
                                    </View>
                                </View>
                                {res.sku.is_member == 1 ? (
                                    <View className="footer1">
                                        <View className="layout1">
                                            <View className="font">会员价</View>
                                        </View>
                                        <View className="small1">￥ {(res.num * res.sku.price * res.sku.discount / 100).toFixed(2)}</View>
                                    </View>
                                ) : (
                                    ''
                                )}
                                {res.sku.is_member == 1 ? (
                                    <View className="footer2">
                                        <View className="layout1">
                                            <Image className="font-img" src={discount}></Image>
                                            <View className="font">抵用券</View>
                                        </View>
                                        {member_level == 1 ? (

                                            <View className="small">已抵用￥ {res.sku.offset_price}</View>
                                        ) : (
                                            ''
                                        )}
                                        {member_level == 2 ? (

                                            <View className="small">已抵用￥ {res.sku.two_offset_price}</View>
                                        ) : (
                                            ''
                                        )}
                                    </View>
                                ) : (
                                    ''
                                )}


                            </View>
                        ))
                    }
                    {/* <View className="footer">
                        <View className="font">会员价</View>
                        <View className="font">￥ 599</View>
                    </View> */}

                    <View className="footer">
                        <View></View>
                        <View className="layout">
                            <View className="smallFont">共优惠</View>
                            <View className="youhuimoner">￥{tempOrderInfo.member_amount}</View>
                            <View >小计</View>
                            <View className="last">￥{tempOrderInfo.paid_amount}</View>
                        </View>
                    </View>
                </View>
                <View className="chunk">
                    <View className="content1">
                        <View className="layout">
                            <View className="shop-free">运费</View>
                            <View className="shop-time">￥{tempOrderInfo.shopping_fee}</View>
                        </View>
                        <View className="layout1">
                            <Picker className="date-picker" value={deliveryTime} mode='date' start={startDeliveryTime} onChange={this.dateChange}>
                                <View className="wrap">
                                    <View className="text-tiem">发货时间</View>
                                    <View className="time-number">{deliveryTime}
                                        {
                                            deliveryTime == '' ? (
                                                <View className="text-tiem1">选择时间</View>
                                            ) : <View></View>
                                        }</View>
                                </View>
                            </Picker>
                        </View>
                    </View>
                </View>
                <View className="goods-time">预计发货后1-2天送达</View>
                <View className="commonfooter">
                    <View style='display:flex;align-items: center;'>
                        <View className="bigmoneyFu">￥</View>
                        <View className="bigmoney" > {tempOrderInfo.paid_amount}</View>
                        <View className="shuoming" >已优惠</View>
                        <View className="lastMoney">￥{tempOrderInfo.member_amount}</View>
                    </View>
                    <View className="wechart" onClick={this.confirmOrder}>微信支付</View>
                </View>
            </View>
        ) : (
            <View></View>
        );
    }
}